﻿using Api.BLL;
using Api.Common;
using Api.Model;
using System.Runtime.Remoting.Messaging;
using System.Web;
using Able.Common.DEncrypt;
using System;
using System.Web.Mvc;

namespace Api.Web.helper
{
    public class Th
    {
        public static int ProjectId => (CurrentProject?.Id).GetValueOrDefault();
        public static Project CurrentProject
        {
            get
            {
                var m = CallContext.GetData("currentProject") as Project;
                if (m == null)
                {
                    var projectId = HttpContext.Current.Request.RequestContext.RouteData.Values["projectId"]?.ToString();
                    if (projectId == null || string.IsNullOrEmpty(projectId.ToString()))
                    {
                        projectId = AjaxParameterHelper.GetParams("projectId");
                    }

                    int id;
                    int.TryParse(projectId, out id);

                    m = ProjectBLL.Current.GetModel(s => s.Id == id && s.UserId == UserId);
                    CallContext.SetData("currentProject", m);
                }
                return m;
            }
        }

        public static User User
        {
            get
            {
                var user = CallContext.GetData(typeof(User).Name) as User;
                if (user == null)
                {
                    var userIdstr = CookieHelper.GetCookie(CookieName.UserId);
                    userIdstr = DESEncrypt.Decrypt(userIdstr);

                    int userId = 0;
                    int.TryParse(userIdstr, out userId);

                    user = UserBLL.Current.GetModel(s => s.Id == userId);
                    User = user;
                }
                return user;
            }
            set { CallContext.SetData(typeof(User).Name, value); }
        }

        /// <summary>
        /// 判断当前是否在某个地址
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="controllerName"></param>
        /// <param name="actionName"></param>
        /// <returns></returns>
        public static bool IsInThisPage(string controllerName = "home", string actionName = "projectlist")
        {
            var name1 = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"]?.ToString();
            var name2 = HttpContext.Current.Request.RequestContext.RouteData.Values["action"]?.ToString();

            if (name1.ToLower() == controllerName.ToLower() &&
                name2.ToLower() == actionName.ToLower())
            {
                return true;
            }
            return false;
        }

        public static int UserId => (User?.Id).GetValueOrDefault();

        public static bool IsLogin
        {
            get { return User != null && UserId > 0; }
        }
    }
}